package com.woniu.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * 自定义域
 *
 * @author WenXin
 * @version 1.0
 * @description: TODO
 * @date 2022/9/5 16:35
 */
public class MyRealmDemo extends AuthorizingRealm {
    //自定义的域类名
    private final String REALMNAME = "MyRealmDemo";

    //授权方法 后授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //通过参数对象 校长对象获取对应的权限信息
        if (principalCollection.getRealmNames().contains(REALMNAME)) {
            //如果进入说明存在自定义域
            String username = principalCollection.getPrimaryPrincipal() + "";
            //模拟数据库去角色表和权限表中查询数据出来，并封装到AuthorizationInfo里面
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            roles.add("manager");
            roles.add("user");
            //权限集合,封装权限
            Set<String> perms = new HashSet<>();
            perms.add("user:add");
            perms.add("user:edit");
            perms.add("user:delete");
            perms.add("user:find");
            //
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setRoles(roles);
            simpleAuthorizationInfo.setStringPermissions(perms);
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证方法 先认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken instanceof UsernamePasswordToken) {
            UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
            String username = usernamePasswordToken.getUsername();
            //获取username后通过dao查询数据库，匹配密码验证是否登录成功
            String password = "123456";
            if (new String(usernamePasswordToken.getPassword()).equals(password)) {
                System.out.println("登陆成功！");
                return new SimpleAuthenticationInfo(username, password, REALMNAME);
            }
        }
        return null;
    }
}
